package com.cochain.rocketmq.controller;

import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RocketProducerController {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping(value = "/rocket")
    public void noTag() {
        // convertAndSend() 发送普通字符串消息
        rocketMQTemplate.convertAndSend("test_topic", "Hello Word");
    }

    @GetMapping(value = "/tagA")
    public void tagA() {
        rocketMQTemplate.convertAndSend("test_topic:tagA", "hello world tagA");
    }

    @GetMapping(value = "/tagB")
    public void tagB() {
        rocketMQTemplate.convertAndSend("test_topic:tagB", "hello world tagB");
    }

    @GetMapping(value = "/syncSend")
    public void syncSend() {
        String json = "发送同步消息";
        SendResult sendResult = rocketMQTemplate.syncSend("test_topic:1", json);
        System.out.println(sendResult);
    }

    @GetMapping(value = "/aSyncSend")
    public void aSyncSend() {
        String json = "发送异步消息";
        SendCallback callback = new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送消息成功");
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送消息失败");
            }
        };
        rocketMQTemplate.asyncSend("test_topic", json, callback);
    }

    @GetMapping(value = "/sendOneWay")
    public void sendOneWay() {
        rocketMQTemplate.sendOneWay("test_topic", "发送单向消息");
    }
}

